<?php
// +----------------------------------------------------------------------
// | CleverPHP [ WE CAN DO IT JUST BeautySoft ]
// +----------------------------------------------------------------------
// | Copyright (c) 2012~2017 http://git.oschina.net/ceiba/CleverPHP All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: ceiba <ceiba_@126.com>
// +----------------------------------------------------------------------

class CacheMongodb{
	protected  $mongoDB;
	public 	   $capped_size=0;
	public 	   $mesg;
	public 	   $cacheDir;
	function __construct($mongoDB=null){
		if ($mongoDB){
			$this->mongoDB=$mongoDB;
		}else{			
			$this->mongoDB=M();
			$this->mongoDB->table_name="static_caches";
			
		}
	}
	//初始化
	protected function _init(){
		if ($this->capped_size){	
				
		}
		if ($this->cacheDir){
			$this->mongoDB->table_name=str_replace("/","_",$this->cacheDir);

		}
		
	}
	
	//写
	public function setCache(string $key,$caches,$expire=0){
		
		if (!$this->mongoDB){
			$this->mesg="数据模型未创建";
			return false;
		}
		
		if(!$caches){
			return $this->delCache($key);
		}
		
		$this->_init();
		$datas["caches"]=$caches;
		$datas["add_time"]=intval(time());
		$datas["cache_id"]=(String)strip_tags($key);
		$where["cache_id"]=(String)strip_tags($key);
		return $this->mongoDB->where($where)->update($datas);
	}
	//读
	public function getCache(string $cache_name){
		if (!$this->mongoDB){
			$this->mesg="数据模型未创建";
			return false;
		}
		$this->_init();
		$where["cache_id"]=(String)strip_tags($cache_name);
		
		$datas= $this->mongoDB->where($where)->find();
		if (isset($datas["caches"])){
			return $datas["caches"];
		}
		
	
	}
	//删
	public function delCache(string $key){
		if (!$this->mongoDB){
			$this->mesg="数据模型未创建";
			return false;
		}
		$this->_init();
		$where["cache_id"]=(String)strip_tags($key);
		return $this->mongoDB->where($where)->del();
	
	}
	//失效
	public function delOverdueCache($lifetime){
		if (!$this->mongoDB){
			$this->mesg="数据模型未创建";
			return false;
		}
		$expire = time() - $lifetime;
		/* $expire = time () - $lifetime;
		 $sql = "delete from `$this->_table where `created_time` < $expire";
		 return mysql_query ( $sql, $this->_db_link ); */
		if (!$this->mongoDB) return false;
		$this->_init();
		$where["add_time"]=array('$lt'>intval($expire));
		return $this->mongoDB->where($where)->del();
	}
	
	
	
	
}